package com.fenqing.leetcode.code.t600_700;

import com.fenqing.annotations.DesignClass;
import com.fenqing.core.design.DesignTopic;

/**
 * @author fenqing
 */
public class Topic707 extends DesignTopic {

    public Topic707(String methods, String params) {
        super(methods, params);
    }

    public static void main(String[] args) {
        Topic707 topic707 = new Topic707(
                """
                        ["MyLinkedList","addAtHead","addAtHead","addAtHead","addAtIndex","deleteAtIndex","addAtHead","addAtTail","get","addAtHead","addAtIndex","addAtHead"]
                        """,
                """
                        [[],[7],[2],[1],[3,0],[2],[6],[4],[4],[4],[5,0],[6]]
                        """
        );
        System.out.println(topic707.run());
    }

    @DesignClass
    public static class MyLinkedList {

        Node head, tail;
        int size;

        public MyLinkedList() {
        }

        public int get(int index) {
            if (index < 0 || index >= size) {
                return -1;
            }
            Node cur = head;
            for (int i = 0; i < index; i++) {
                cur = cur.next;
            }
            return cur.val;
        }

        public void addAtHead(int val) {
            Node node = new Node();
            node.val = val;
            node.next = head;
            if (head != null) {
                head.prev = node;
            } else {
                tail = node;
            }
            head = node;
            size++;
        }

        public void addAtTail(int val) {
            Node node = new Node();
            node.val = val;
            node.prev = tail;
            if (tail != null) {
                tail.next = node;
            } else {
                head = node;
            }
            tail = node;
            size++;
        }

        public void addAtIndex(int index, int val) {
            if (index < 0 || index >= size) {
                return;
            }
            Node cur = head;
            for (int i = 0; i < index - 1; i++) {
                cur = cur.next;
            }
            Node node = new Node();
            node.val = val;
            node.next = cur.next;
            node.prev = cur;
            if (cur.next != null) {
                cur.next.prev = node;
            }
            cur.next = node;
            size++;
        }

        public void deleteAtIndex(int index) {
            if (index < 0 || index >= size) {
                return;
            }
            Node cur = head;
            for (int i = 0; i < index; i++) {
                cur = cur.next;
            }
            if (cur.prev != null) {
                cur.prev.next = cur.next;
            }
            if (cur.next != null) {
                cur.next.prev = cur.prev;
            }
            size--;
        }

        public static class Node {
            int val;
            Node prev, next;
        }
    }
}
